package middlewares

import (
	"context"
	"final-url/entity"
	"log"
	"net/http"
	"runtime/debug"
	"strings"
)

func NewEnv(config *entity.Config) func(next http.HandlerFunc) http.HandlerFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			defer func() {
				if err := recover(); err != nil {
					log.Printf("panic: %v[%s]", err, debug.Stack())
					msg := http.StatusText(http.StatusInternalServerError)
					if strings.ToLower(r.Header.Get("Content-Type")) == "application/json" {
						msg = "{\"success\":false,\"msg\":\"" + msg + "\"}"
					}
					http.Error(w, msg, http.StatusInternalServerError)
				}
			}()

			next(w, r.WithContext(context.WithValue(r.Context(), "config", config)))
		}
	}
}
